package com.gadgets.framework.common.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

public class PinYinUtil {

    private static final HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();

    static {
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    }

    public static String pinYintrasnlate(String targetString){
        if(StringUtils.isBlank(targetString)){
            return "";
        }
        StringBuilder pinyinContainer = new StringBuilder();
        char[] characters = targetString.toCharArray();
        for (char character : characters) {
            // if chinese
            if(character>128){
                try{
                    String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(character,format);
                    if(null==pinyin || pinyin.length==0){
                        pinyinContainer.append(character);
                    }else {
                        pinyinContainer.append(pinyin[0]);
                        // word pinyin split by character '
                        pinyinContainer.append("'");
                    }
                }catch (Exception e){
                    pinyinContainer.append(character);
                }
            }else{
                pinyinContainer.append(character);
            }
        }
        return pinyinContainer.toString();
    }

}
